<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
<%
String path = request.getContextPath();
String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
%>
<%
	pageContext.setAttribute("APP_PATH", request.getContextPath());
 %>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
  <head>
    
    <title>社员列表</title>
    <script type="text/javascript" src="${APP_PATH}/static/bootstrap-3.3.7-dist/js/jquery-3.2.1.min.js"></script>
    <link rel="stylesheet" href="${APP_PATH}/static/bootstrap-3.3.7-dist/css/bootstrap.min.css">
	<script type="text/javascript" src="${APP_PATH}/static/bootstrap-3.3.7-dist/js/bootstrap.min.js"></script>
  </head>
  
  <body>
  
  <!-- 员工添加的模态框 -->
<div class="modal fade" id="empAddModal" tabindex="-1" role="dialog" aria-labelledby="myModalLabel">
  <div class="modal-dialog" role="document">
    <div class="modal-content">
      <div class="modal-header">
        <button type="button" class="close" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">&times;</span></button>
        <h4 class="modal-title" id="myModalLabel">社员添加</h4>
      </div>
      <div class="modal-body">
        <form class="form-horizontal">
		  <div class="form-group">
		    <label for="empName_add_input" class="col-sm-2 control-label">社员姓名</label>
		    <div class="col-sm-10">
		      <input type="text" name="empName" class="form-control" id="empName_add_input" placeholder="姓名">
		      <span class="help-block"></span>
		    </div>
		  </div>
		  <div class="form-group">
		    <label for="email_add_input" class="col-sm-2 control-label">邮箱</label>
		    <div class="col-sm-10">
		      <input type="email" name="email"  class="form-control" id="email_add_input" placeholder="邮箱@">
		      <span class="help-block"></span>
		    </div>
		  </div>
		  <div class="form-group">
		    <label  class="col-sm-2 control-label">性别</label>
		    <div class="col-sm-10">
		      	<label class="radio-inline">
				  <input type="radio" checked="checked" name="gender" id="gender1_add_input" value="M"> 男
				</label>
				<label class="radio-inline">
				  <input type="radio" name="gender" id="gender2_add_input" value="F"> 女
				</label>
		    </div>
		  </div>
		  <div class="form-group">
		    <label  class="col-sm-2 control-label">社部名称</label>
		    <div class="col-sm-4">
		      	<select class="form-control" name="dId" id="dept_add_select" >
		
				</select>
		    </div>
		  </div>
		</form>
      </div>
      <div class="modal-footer">
        <button type="button" class="btn btn-default" data-dismiss="modal">关闭</button>
        <button type="button" class="btn btn-primary" id="emp_save_btn">保存</button>
      </div>
    </div>
  </div>
</div>
  
  
<!-- 员工修改的模态框 -->
<div class="modal fade" id="empUpdateModal" tabindex="-1" role="dialog" aria-labelledby="myModalLabel">
  <div class="modal-dialog" role="document">
    <div class="modal-content">
      <div class="modal-header">
        <button type="button" class="close" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">&times;</span></button>
        <h4 class="modal-title" >社员修改</h4>
      </div>
      <div class="modal-body">
        <form class="form-horizontal">
		  <div class="form-group">
		    <label for="empName_add_input" class="col-sm-2 control-label">社员姓名</label>
		    <div class="col-sm-10">
		      <p class="form-control-static" id="empName_update_static"></p>
		    </div>
		  </div>
		  <div class="form-group">
		    <label for="email_add_input" class="col-sm-2 control-label">邮箱</label>
		    <div class="col-sm-10">
		      <input type="email" name="email"  class="form-control" id="email_update_input" placeholder="邮箱@">
		      <span class="help-block"></span>
		    </div>
		  </div>
		  <div class="form-group">
		    <label  class="col-sm-2 control-label">性别</label>
		    <div class="col-sm-10">
		      	<label class="radio-inline">
				  <input type="radio" checked="checked" name="gender" id="gender1_update_input" value="M"> 男
				</label>
				<label class="radio-inline">
				  <input type="radio" name="gender" id="gender2_update_input" value="F"> 女
				</label>
		    </div>
		  </div>
		  <div class="form-group">
		    <label  class="col-sm-2 control-label">社部名称</label>
		    <div class="col-sm-4">
		      	<select class="form-control" name="dId" id="dept_update_select" >
		
				</select>
		    </div>
		  </div>
		</form>
      </div>
      <div class="modal-footer">
        <button type="button" class="btn btn-default" data-dismiss="modal">关闭</button>
        <button type="button" class="btn btn-primary" id="emp_update_btn">更新</button>
      </div>
    </div>
  </div>
</div>
  
  <!-- 页面显示 -->
  	<div class="container">
  		<!-- 标题 -->
  		<div class="row"></div>
  		<div class="col-md-12">
  			<h1>社员管理</h1>
  		</div>
  		<!-- 按钮 -->
  		<div class="row">
  			<div class="col-md-4 col-md-offset-8">
  				<button class="btn btn-primary" id="emp_add_modal_btn">新增</button>
  				<button class="btn btn-danger">删除</button>
  			</div>
  		</div>
  		<!-- 显示表格数据 -->
  		<div class="row">
  			<div class="col-md-12">
  				<table class="table table-striped table-hover" id="emps_table">
  					<thead>
	  					<tr>
	  						<th>#</th>
	  						<th>empName</th>
	  						<th>gender</th>
	  						<th>email</th>
	  						<th>deptName</th>
	  						<th>操作</th>
	  					</tr>
  					</thead>
  					<tbody>
  					
  					</tbody>
  				</table>
  			</div>
  		</div>
  		<!-- 显示分页信息 -->
  		<div class="row">
  			<!-- 分页文字信息 -->
  			<div class="col-md-6" >
  				<nav aria-label="Page navigation">
				  <ul class="pagination">
				  	<li><a id="page_info_area"></a></li>
				  </ul>
				</nav>
  			</div>
  			<!-- 分页条 -->
  			<div class="col-md-6" id="page_nav_area">
  	
  			</div>
  		</div>
  	</div>
  
  <script type="text/javascript">
  	
  	//保存一个全局的总记录数
  	var totalRecord,currentPage;
  
  	//1.页面加载完成后，直接发送一个ajax请求，请求分页数据
  	$(function(){
		to_page(1);
  	});
  	//跳转页面逻辑
  	function to_page(pn){
  		$.ajax({
  			url: "${APP_PATH}/emps",
  			data:"pn="+pn,
  			type: "GET",
  			success:function(result){
  				console.log(result);
  				//1.解析并显示员工数据
  				build_emps_table(result);
  				//2.解析并显示分页信息
  				build_page_info(result)
  				//3.解析显示分页条数据
  				build_page_nav(result);
  			}
  		});
  	}
  	
  	
  	function build_emps_table(result){
  	
  		//首先清空表格
  		$("#emps_table tbody").empty();
  		
  		var emps = result.extend.pageInfo.list;
  		$.each(emps,function(index,item){
  			var empIdTd = $("<td></td>").append(item.empId);
  			var empNameTd = $("<td></td>").append(item.empName);
  			var genderTd = $("<td></td>").append(item.gender=='M'?"男":"女");
  			var emailTd = $("<td></td>").append(item.email);
  			if(item.department !=null){
  				var departmentTd = $("<td></td>").append(item.department.deptName);
  			}else{
  				var departmentTd = $("<td></td>").append("部门待定");
  			}
  			
  			/*
  			<button class="btn btn-primary btn-xs">
	  			<span class="glyphicon glyphicon-pencil" aria-hidden="true"></span>
	  			编辑
	  	    </button>
  			*/
  			var editBtn = $("<button></button>").addClass("btn btn-primary btn-xs edit_btn")
  							.append($("<span></span>").addClass("glyphicon glyphicon-pencil"))
  							.append(" 編輯");
  			//为编辑按钮添加自定义属性，来表示当前id	
  			editBtn.attr("edit-id",item.empId);
  			var delBtn = $("<button></button>").addClass("btn btn-danger btn-xs delete_btn")
  							.append($("<span></span>").addClass("glyphicon glyphicon-trash"))
  							.append(" 刪除");
  			delBtn.attr("del-id",item.empId);
  			var btnTd = $("<td></td>").append(editBtn).append(" ").append(delBtn);
  			
  			$("<tr></tr>").append(empIdTd)
  			.append(empNameTd)
  			.append(genderTd)
  			.append(emailTd)
  			.append(departmentTd)
  			.append(btnTd)
  			.appendTo("#emps_table tbody");
  		});
  	}
  	//解析显示分页信息
  	function build_page_nav(result){
  		
  		$("#page_info_area").empty();
  	
  		$("#page_info_area")
  		.append("当前第"+result.extend.pageInfo.pageNum+"页,总"+result.extend.pageInfo.pages+"页,总"+result.extend.pageInfo.total+"条记录");
  		totalRecord = result.extend.pageInfo.total;
  		currentPage=result.extend.pageInfo.pageNum;
  		 	}
  	//解析显示分页条
  	function build_page_info(result){
  	
  		$("#page_nav_area").empty();
  		
  		var ul = $("<ul></ul>").addClass("pagination");
  		//首页与前一页显示逻辑
  		var firstPageLi = $("<li></li>").append($("<a></a>").append("首页").attr("href","#"));

  		if(result.extend.pageInfo.hasPreviousPage == false){
  			firstPageLi.addClass("disabled");
  		}else{
  			var prePageLi = $("<li></li>").append($("<a></a>").append("&laquo;"));
  			prePageLi.click(function(){
  				to_page(result.extend.pageInfo.pageNum -1);
  			});
  			firstPageLi.click(function(){
	  			to_page(1);
	  		});
  		}
  		//末页与后一页显示逻辑
  		var lastPageLi = $("<li></li>").append($("<a></a>").append("末页").attr("href","#"));
  		
  		if(result.extend.pageInfo.hasNextPage == false){
  			lastPageLi.addClass("disabled");
  		}else{
  			var nextPageLi = $("<li></li>").append($("<a></a>").append("&raquo;"));
  			nextPageLi.click(function(){
  				to_page(result.extend.pageInfo.pageNum +1);
  			});
			lastPageLi.click(function(){
			  	to_page(result.extend.pageInfo.pages);
  			});
  		}
  		//构造添加首页和前一页
  		ul.append(firstPageLi).append(prePageLi);
  		//遍历添加ul中页码提示
  		$.each(result.extend.pageInfo.navigatepageNums,function(index,item){
  			var numLi = $("<li></li>").append($("<a></a>").append(item));
  			if(result.extend.pageInfo.pageNum == item){
  				numLi.addClass("active");
  			}
  			numLi.click(function(){
  				to_page(item);
  			});
  			ul.append(numLi);
  		});
  		//构造添加后一页和末页
  		ul.append(nextPageLi).append(lastPageLi);
  		
  		var navEle = $("<nav></nav>").append(ul);
  		
  		$("#page_nav_area")
  		.append(navEle);
  	}
  	
  	
  	//点击新增按钮弹出模态框
  	$("#emp_add_modal_btn").click(function(){
  		//表单数据重置
  	  	$("#empAddModal form")[0].reset();
  	
  		//发送ajax请求显示下拉列表
  		getDepts("#dept_add_select");
  		//弹出模态框
  		$("#empAddModal").modal({
  			backdrop:"static"
  		});
  	});
  	
  	//发送ajax请求获取部门数据
  	function getDepts(ele){
  		//清除校验状态 以及部门选择 
   /* 		$("#empName_add_input").parent().removeClass("has-success has-error");
  		$("#empName_add_input").next("span").text(""); 
  		
  		$("#email_add_input").parent().removeClass("has-success has-error");
  		$("#email_add_input").next("span").text(""); 
  		 */
  	  	$(ele).empty(); 
 		
  	  	
  	  	//发送ajax请求
  		$.ajax({
  			url:"${APP_PATH}/depts",
  			type:"GET",
  			success:function(result){
  				//console.log(result)
  				//在下拉列表中显示部门信息
  				//$("#dept_add_select")
  				$.each(result.extend.depts,function(){
  					var optionEle = $("<option></option>").append(this.deptName).attr("value",this.deptId);
  					optionEle.appendTo(ele);
  				});
  			}
  		});
  	}
  	//校验表单数据
  	function validate_add_form(){
  		var empName = $("#empName_add_input").val();
  		var regName = /(^[a-zA-Z0-9_-]{6,16}$)|(^[\u2E80-\u9FFF]{2,5})/;
  		if(!regName.test(empName)){
  			//alert("6-16英文或2-5中文");
  			show_validate_msg("#empName_add_input","error","用户名格式为6-16位英文或2-5位中文");
  			return false;
  		}else if(!$("#emp_save_btn").attr("ajax-va")=="error"){
  		
  			show_validate_msg("#empName_add_input","success","用户名格式正确");
  		}
  		var email = $("#email_add_input").val();
  		var regEmail = /^([a-z0-9_\.-]+)@([\da-z\.-]+)\.([a-z\.]{2,6})$/;
  		if(!regEmail.test(email)){
  			//alert("邮箱格式不正确");
  			show_validate_msg("#email_add_input","error","邮箱格式不正确");
  			return false;
  		}else{
  			show_validate_msg("#email_add_input","success","邮箱格式正确");
  		}
  		return true;
  	}
  	
  	//$("#empName_add_input").change(validate_add_form());
  	//显示数据格式是否正确
  	function show_validate_msg(ele,status,msg){
  		//清除校验状态
  		$(ele).parent().removeClass("has-success has-error");
  		$(ele).next("span").text("");
  		
  		if("success"==status){
  			$(ele).parent().addClass("has-success");
  			$(ele).next("span").text(msg);
  			
  		}else if("error"==status){
  			$(ele).parent().addClass("has-error");
  			$(ele).next("span").text(msg);
  		}
  	}
  	
  	//邮箱change校验
  	$("#email_add_input").change(function(){
  		var email = $("#email_add_input").val();
  		var regEmail = /^([a-z0-9_\.-]+)@([\da-z\.-]+)\.([a-z\.]{2,6})$/;
  		if(!regEmail.test(email)){
  			//alert("邮箱格式不正确");
  			show_validate_msg("#email_add_input","error","邮箱格式不正确");
  			return false;
  		}else{
  			show_validate_msg("#email_add_input","success","邮箱格式正确");
  		}
  		return true;
  	});
  	
  	//校验用户名是否可用
  	$("#empName_add_input").change(function(){
  		var empName = this.value;
  		
  		var empName = $("#empName_add_input").val();
			  		var regName = /(^[a-zA-Z0-9_-]{6,16}$)|(^[\u2E80-\u9FFF]{2,5})/;
			  		if(!regName.test(empName)){
			  			//alert("6-16英文或2-5中文");
			  			show_validate_msg("#empName_add_input","error","用户名格式为6-16位英文或2-5位中文");
			  			$("#emp_save_btn").attr("ajax-va","fail");
			  		}else {
				  		//发送ajax请求
				  		$.ajax({
				  			url:"${APP_PATH}/checkuser",
				  			data:"empName="+empName,
				  			type:"POST",
				  			success:function(result){
				  				if(result.code==100){
							  		show_validate_msg("#empName_add_input","success","用户名可用");
							  		$("#emp_save_btn").attr("ajax-va","success");
				  				}else{
				  					show_validate_msg("#empName_add_input","error","用户名已存在!");
				  					$("#emp_save_btn").attr("ajax-va","error");
				  				}
				  			}
				  		});
				  		 		}
				  		
  	});
  	//1.首先判断用户校验的ajax请求是否成功
  	//保存按钮点击事件
  	$("#emp_save_btn").click(function(){

  		//1.模态框中填写的数据发送给服务器进行保存
  		//1.1先对要提交数据进行校验
  		if(!validate_add_form()){
  			return false;
  		}
  		if($(this).attr("ajax-va")=="error"){
  			$("#empName_add_input").parent().removeClass("has-success has-error");
  			$("#empName_add_input").next("span").text(""); 
  			show_validate_msg("#empName_add_input","error","用户名已存在!");
  			return false;
  		}
  		
  		//2.发送ajax请求保存员工
  		//alert($("#empAddModal form").serialize());
  	 	$.ajax({
  			url:"${APP_PATH}/emp",
  			type:"POST",
  			data:$("#empAddModal form").serialize(),
  			success:function(result){
  				if(result.code == 100)
  				{
	  				//alert($("#empAddModal form").serialize());
	  				//处理成功
	  				//1.关闭模态框
	  				$('#empAddModal').modal('hide');
	  				//2.来到最后一页
	  				to_page(totalRecord);
  				}else{
  					//显示后端校验失败信息
  					if(undefined!=result.extend.errorFields.email){
  						//显示邮箱错误信息
  						show_validate_msg("#email_add_input","error",result.extend.errorFields.email+"(你这波操作很6然而没什么卵用~)");
  					}
  					if(undefined!=result.extend.errorFields.empName){
  						//显示姓名错误信息
  						show_validate_msg("#empName_add_input","error",result.extend.errorFields.empName+"(偷鸡可不是什么好习惯)");
  					}
  				}
  			}
  		}); 
  	});
  	
  	//为修改绑定单击事件，这里使用on方法
  	$(document).on("click",".edit_btn",function(){
  		
  		//alert("edit");
  		//$("#empUpdateModal").empty();
  		
  		//1.发送ajax请求显示下拉列表
  		getDepts("#empUpdateModal select");
  		//2.ajax请求获取员工信息
  		getEmp($(this).attr("edit-id"));
  		//3.把员工id传入btn
  		$("#emp_update_btn").attr("edit-id",$(this).attr("edit-id"));
  		//弹出模态框
  		$("#empUpdateModal").modal({
  			backdrop:"static"
  		});
  	});
  	
  	function getEmp(id){
		$.ajax(
		{
			url:"${APP_PATH}/emp/"+id,
			type:"GET",
			success:function(result){
				//console.log(result);
				var empData = result.extend.emp;
				$("#empName_update_static").text(empData.empName);
				$("#email_update_input").val(empData.email);
				$("#empUpdateModal input[name=gender]").val([empData.gender]);
				$("#empUpdateModal select").val([empData.dId]);
			}
		})
  	};
  	$("#emp_update_btn").click(function(){
  		//验证邮箱是否合法
  		//1.校验邮箱信息
  		var email = $("#email_update_input").val();
  		var regEmail = /^([a-z0-9_\.-]+)@([\da-z\.-]+)\.([a-z\.]{2,6})$/;
  		if(!regEmail.test(email)){
  			//alert("邮箱格式不正确");
  			show_validate_msg("#email_update_input","error","邮箱格式不正确");
  			return false;
  		}else{
  			show_validate_msg("#email_update_input","success","邮箱格式正确");
  		}
  		//2.发送ajax请求保存更新员工数据
  		$.ajax({
  			url:"${APP_PATH}/emp/"+$(this).attr("edit-id"),
  			type:"PUT",
  			data:$("#empUpdateModal form").serialize(),
  			success:function(result){
  			
  				//关闭对话框
  				$("#empUpdateModal").modal("hide");
  				//回到本页
  				to_page(currentPage);
  			}
  		});
  	});
  	
  	//删除按钮操作
  	$(document).on("click",".delete_btn",function(){
  			var empName=$(this).parents("tr").find("td:eq(1)").text();
  			var empId=$(this).attr("del-id");
  			if(confirm("确认删除["+empName+"]么？")){
	  			$.ajax({
	  				url:"${APP_PATH}/emp/"+empId,
	  				type:"DELETE",
	  				success:function(result){
	  					alert(result.msg);
	  					to_page(currentPage);
	  				}
	  			});
  			}
  	});
  	
  </script>
  </body>
</html>
